/**
 * 
 */
package com.rtsp.tool.snatch;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author w.weizhen
 * 
 */
public class RunnableMain {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		
		JSONArray datas = new JSONArray();
		datas.add(JSON.parseObject("{code:'L12051310', url:'rtsp://admin:19870513qq@192.168.12.104:554/Streaming/Channels/101'}"));
		datas.add(JSON.parseObject("{code:'135152559', url:'rtsp://admin:88888888b@192.168.12.105:554/Streaming/Channels/101'}"));
		datas.add(JSON.parseObject("{code:'F93882634', url:'rtsp://admin:88888888b@192.168.12.106:554/Streaming/Channels/101'}"));
		
		for (int i = 0; i < datas.size(); i++) 
		{
			JSONObject data = datas.getJSONObject(i);
			RtspSnatchRunnable tsr = new RtspSnatchRunnable(data.getString("code"), data.getString("url"));
			service.scheduleAtFixedRate(tsr, 5, 1000, TimeUnit.MILLISECONDS);
		}
		
//		RtspSnatchRunnable tsr00 = new RtspSnatchRunnable("tsr00");
//		RtspSnatchRunnable tsr01 = new RtspSnatchRunnable("tsr01");
//		RtspSnatchRunnable tsr02 = new RtspSnatchRunnable("tsr02");
//		RtspSnatchRunnable tsr03 = new RtspSnatchRunnable("tsr03");
//		
//        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
//        service.scheduleAtFixedRate(tsr00, 5, 2000, TimeUnit.MILLISECONDS); 
//        service.scheduleAtFixedRate(tsr01, 2, 1000, TimeUnit.MILLISECONDS); 
//        service.scheduleAtFixedRate(tsr02, 3, 5000, TimeUnit.MILLISECONDS); 
//        service.scheduleAtFixedRate(tsr03, 4, 3000, TimeUnit.MILLISECONDS); 
		
	}
	
	static class RtspSnatchRunnable implements Runnable{ 
		
		private static String rtsp_url;
		private static String code;
		// 工作目录
		private static final String user_dir = System.getProperty("user.dir") + File.separator;
		private static final String data_path = user_dir + "data" + File.separator;
		
		public static FFmpegFrameGrabber grabber;
		
		RtspSnatchRunnable(String code, String rtsp_url)
		{
			this.rtsp_url = rtsp_url;
			this.code = code;
//			data_path = data_path + code + File.separator;
			File data_file = new File(data_path, code);
			if(!data_file.exists())
			{
				data_file.mkdir();
			}
			try {
				grabber = FFmpegFrameGrabber.createDefault(rtsp_url);
				grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式，不然会丢包很严重
				grabber.setImageWidth(1280);
				grabber.setImageHeight(720);
				grabber.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() 
		{
			try {
				Frame frame = grabber.grabImage();
				if (frame != null) {
					File outPut = new File(data_path + code + File.separator + System.currentTimeMillis() + ".jpeg");
					ImageIO.write(FrameToBufferedImage(frame), "jpeg", outPut);
//					 grabber.stop();
//					 grabber.release();
//					System.out.println("图片已保存");
					// break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		private static void work()
		{
			
			
			
		}
		
//		private static void work()
//		{
//			try {
//				FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(rtsp_url);
//				grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式，不然会丢包很严重
//				grabber.setImageWidth(1280);
//				grabber.setImageHeight(720);
//				grabber.start();
//				
////				//1.播放视频
////				CanvasFrame canvasFrame = new CanvasFrame("摄像机");
////				canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
////				canvasFrame.setAlwaysOnTop(true);
////				OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
////				while (true) {
////					Frame frame = grabber.grabImage();
////					Mat mat = converter.convertToMat(frame);
////					canvasFrame.showImage(frame);
////				}
//				
//				// 2.帧截图
//				while (true) {
//					Frame frame = grabber.grabImage();
//					if (frame != null) {
//						File outPut = new File(data_path + code + File.separator + System.currentTimeMillis() + ".jpeg");
//						ImageIO.write(FrameToBufferedImage(frame), "jpeg", outPut);
////						 grabber.stop();
////						 grabber.release();
////						System.out.println("图片已保存");
//						// break;
//					}
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		
		/**
		 * 创建BufferedImage对象
		 */
		public static BufferedImage FrameToBufferedImage(Frame frame) {
			Java2DFrameConverter converter = new Java2DFrameConverter();
			BufferedImage bufferedImage = converter.getBufferedImage(frame);
//			bufferedImage=rotateClockwise90(bufferedImage);//将图片旋转90度
			return bufferedImage;
		}

		/**
		 * 处理图片，将图片旋转90度。
		 */
		public static BufferedImage rotateClockwise90(BufferedImage bi) {
			int width = bi.getWidth();
			int height = bi.getHeight();
			BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());
			for (int i = 0; i < width; i++)
				for (int j = 0; j < height; j++)
					bufferedImage.setRGB(j, i, bi.getRGB(i, j));
			return bufferedImage;
		}
		
	}
	
}